<?php

namespace app\admin\controller\service;

use app\admin\model\Admin;
use app\common\model\TechnicianService;
use Throwable;
use app\common\controller\Backend;

/**
 * 服务项目管理
 */
class Service extends Backend
{
    /**
     * Service模型对象
     * @var object
     * @phpstan-var \app\admin\model\service\Service
     */
    protected object $model;

    protected string|array $defaultSortField = 'service_id,desc';

    protected array $withJoinTable = ['class', 'area'];

    protected array|string $preExcludeFields = ['create_time', 'update_time'];

    protected string|array $quickSearchField = ['service_name'];
    protected array $noNeedPermission = ['index2', 'index3', 'addService'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\service\Service;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->with($this->withJoinTable)
            ->where($this->isAgentWhere())
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['class' => ['class_name']]);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'is_agent' => $this->auth->getInfo()['is_agent']
        ]);
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index3(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->with($this->withJoinTable)
            ->where('area_id', 0)
            ->where('type', 1)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['class' => ['class_name']]);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'is_agent' => $this->auth->getInfo()['is_agent']
        ]);
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index2(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        $technician_id = $this->request->param('technician_id');
        $type = $this->request->param('type');

        $model = $this->model
            ->with($this->withJoinTable)
            ->where('service_status', 1)
            ->where('type', 1);
        if (!$this->auth->isSuperAdmin()) {
            $model->whereIn('area_id', [0, $this->auth->getInfo()['bind_city_id']]);
        }
        $service_ids = TechnicianService::where('technician_id', $technician_id)->column('service_id');
        if ($type == 'notExist') {
            $model->whereNotIn('service_id', $service_ids);
        } else {
            $model->whereIn('service_id', $service_ids);
        }
        $res = $model->select()->each(function ($item) {
            $item->service_cover_img = IMAGE_URL . $item->service_cover_img;
            return $item;
        });

        $this->success('', [
            'list' => $res,
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */


    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate)
                            $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $adminInfo = $this->auth->getInfo();
                if (isset($adminInfo['is_agent']) && $adminInfo['is_agent'] != 1) {
                    $data['service_is_check'] = 1;
                }
                $data['area_id'] = $this->auth->getInfo()['bind_city_id'];
                $data['service_carousel_imgs'] = implode(',', $data['service_carousel_imgs']);
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk = $this->model->getPk();
        $id = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate)
                            $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    public function addService()
    {
        $ids = $this->request->param('ids');

        $serviceModel = new \app\admin\model\service\Service();
        $info = $serviceModel->whereIn('service_id', $ids)->select()->toArray();
        foreach ($info as &$v) {
            unset($v['service_id']);
            $v['area_id'] = $this->auth->bind_city_id;
            $v['create_time'] = date("Y-m-d H:i:s", time());
            $v['update_time'] = date("Y-m-d H:i:s", time());
        }
        unset($v);
        $ret = $serviceModel->saveAll($info);
        if (!$ret)
            $this->error('添加失败');
        $this->success('添加成功');
    }
}